﻿using System.Globalization;
using KPIS.GERP.MVC.Classes;
using KPIS.GERP.MVC.Models;
using KPIS.GERP.SERVICE.DAL;
using KPIS.GERP.SERVICE.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KPIS.GERP.MVC.Controllers
{
    public class AbsenceController : Controller
    {
        public static string absence_seq;
        private GERPContext db = new GERPContext();
        public SsMng ssMng = new SsMng();

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
         
        [HandleError]
        public ActionResult Index()
        {
            string emp_seq = ssMng.EmpSeq;
            string bgm_year = (new ThaiBuddhistCalendar().GetYear(DateTime.Now)).ToString();
            List<hrm_ps_absence> lst;
            try
            { 
                using (var db = new GERPContext())
                {
                    lst = db.hrm_ps_absence.OrderByDescending(o=>o.absence_seq).ToList();
                }
            }catch(Exception ex)
            {
                ex.Data.Add("Error message", "มีปัญหาในการเชื่อมต่อฐานข้อมูล"); 
                throw ex;
            }
            ViewBag.AbsenceTypes = AbsenceTypeDataSource(); 
            return View(lst);
        }

        public ActionResult CreateAbsence()
        {
            ViewBag.AbsenceTypes = AbsenceTypeDataSource();
            ViewBag.requestTitle = DefaultApprovalTitle();
            return View();
        }

        [HttpPost]
        public ActionResult CreateAbsence(hrm_ps_absence item, int? absence_type_seq = null, string requestTitle = "", string requesterEmpSeq = null)
        {
            if (!item.start_date.HasValue)
            {
                ViewBag.Message = "กรุณาเลือกวันเริ่มลา";
            }
            else if (!item.end_date.HasValue)
            {
                ViewBag.Message = "กรุณาเลือกวันสิ้นสุดการลา";
            }
            else if (string.IsNullOrWhiteSpace(requesterEmpSeq))
            {
                ViewBag.Message = "กรุณาเลือกผู้ขอลา";
            }
            else
            {
                requestTitle = string.IsNullOrWhiteSpace(requestTitle) ? DefaultApprovalTitle() : requestTitle;
                item.emp_seq = Convert.ToInt32(requesterEmpSeq);
                item.created_by = ssMng.EmpSeqI;
                try
                {
                    using (var wf = new CheckRulesServiceIisRef.CheckRulesServiceClient())
                    {
                        var req = wf.GetRequestData(item.emp_seq.ToString(), item.absence_type_seq.ToString(),
                                                    (DateTime) item.start_date, (DateTime) item.end_date, 
                                                    item.contact_address, item.description,
                                                    item.created_by.ToString(), item.start_time, item.end_time, 
                                                    requestTitle, out absence_seq);

                        ViewBag.Message = req;
                        ViewBag.Sequence = absence_seq;

                        if (!String.IsNullOrEmpty(absence_seq))
                            item.absence_seq = Convert.ToInt32(absence_seq);
                    }

                }
                catch (HttpException ex)
                {
                    ex.Data.Add("Error message", "อินเตอร์เน็ตไม่สามารถใช้งานได้");
                    throw ex;
                }
                catch (Exception ex)
                {
                    ex.Data.Add("Error message", "ไม่สามารถใช้งานได้เนื่องจาก:" + ex.Message);
                    throw ex;
                }
            }

            ViewBag.AbsenceTypes = AbsenceTypeDataSource(absence_type_seq);

            ViewBag.requestTitle = requestTitle;

            if (item.absence_seq != 0)
                return RedirectToAction("ViewDetails", new { RefSeq = item.absence_seq });

            return View(item);
        }

        public ActionResult Confirm(int? emp_seq, int absence_seq, string status, string requestTitle, int? absence_type_seq = null)
        {
            //requestTitle = string.IsNullOrWhiteSpace(requestTitle) ? DefaultApprovalTitle() : requestTitle;
            if(status == "D")
            {
                new Absence().UpdateStatusHrmPsAbsence(absence_seq.ToString(), "D", ssMng.EmpSeq);
                return RedirectToAction("Index", "Absence");
            }
            else if (String.IsNullOrWhiteSpace(emp_seq.ToString()) || 
                String.IsNullOrWhiteSpace(absence_seq.ToString()) || 
                String.IsNullOrWhiteSpace(status) ||
                String.IsNullOrWhiteSpace(requestTitle))
            {
                ViewBag.Message = "รูปแบบข้อมูลไม่ถูกต้อง";
                return RedirectToAction("CreateAbsence", "Absence");
            }
            else
            {
                hrm_ps_absence absence = null;
                SendApproval app = new SendApproval();
                app.Title = requestTitle;
                app.AbsenceSeq = absence_seq;
                app.EmpSeq = emp_seq.Value;

                app.Status = status;
                if(absence_type_seq == null)
                    using (var db = new GERPContext())
                    {
                        absence = db.hrm_ps_absence.Find(absence_seq);
                        if (absence == null || absence.absence_type_seq == null)
                        {
                            throw new Exception("หาข้อมูลคำขอลาไม่พบ");
                        } 
                        absence_type_seq = absence.absence_type_seq;
                    } 

                try
                {
                    int createdBy = absence != null && absence.created_by.HasValue ? absence.created_by.Value : ssMng.EmpSeqI;
                    int requestBy = absence.emp_seq.Value;

                    using (var serviceClient = new ApprovalServiceIisRef.ServiceClient())
                    {
                        string outMessage;
                        serviceClient.CreateAbsenceTask(app.Title, requestBy, app.AbsenceSeq, app.Status, absence_type_seq.Value, "A", createdBy, out outMessage);
                        ViewBag.Message = outMessage;
                    }
                }
                catch (HttpException ex)
                {
                    ex.Data.Add("Error message", "อินเตอร์เน็ตไม่สามารถใช้งานได้:" + ex.Message);
                    throw ex;
                }
                catch (Exception ex)
                {
                    ex.Data.Add("Error message", "ไม่สามารถใช้งานได้เนื่องจาก:" + ex.Message);
                    throw ex;
                }
                return RedirectToAction("ViewDetails", "Absence", new { RefSeq = absence_seq });
            }
        }

        public ActionResult ViewDetails(int RefSeq)
        {
            approval_task approvalTaskModel;
            hrm_ps_absence hrmPsAbsence;
            using (var db = new GERPContext())
            {
                hrmPsAbsence = db.hrm_ps_absence.Find(RefSeq);
                ViewBag.AbsenceModel = hrmPsAbsence;
                approvalTaskModel = new ApprovalTaskDal().GetApprovalTask(new approval_task {Reference = new approval_reference {ref_seq = RefSeq, rule_approve_type_seq = hrmPsAbsence.absence_type_seq.Value}}).FirstOrDefault();
            }
            approval_task model = null;
            using (var serviceClient = new ApprovalServiceWcfIisRef.AbsenceApprovalWCFClient())
            {
                var data = serviceClient.GetTasks();
                model = (from a in data
                         where a.Reference.ref_seq == RefSeq && a.Reference.rule_approve_group_seq == 1
                         select a).FirstOrDefault();
                if(model == null)
                    using (var serviceClientWf = new ApprovalServiceIisRef.ServiceClient())
                    {
                        try
                        {
                            model = serviceClientWf.GetApprovalTask(approvalTaskModel.WfInstantId);
                        } catch (Exception ex)
                        {

                        }
                    }
            }
            return View(model);
        }

        public IEnumerable<SelectListItem> AbsenceTypeDataSource(int? absenceTypeSeq = null)
        {
            return new AbsenceTypes().GetAllAbsenceTypes()
                .Select(c => new SelectListItem
                {
                    Value = c.absence_type_seq.ToString(),
                    Text = c.absence_type_name.ToString(),
                    Selected = absenceTypeSeq.HasValue && c.absence_type_seq == absenceTypeSeq
                });
        }

        public string DefaultApprovalTitle()
        {
            return "คำขอลาของ" + ssMng.UserName;
        }
    }
}
